<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Courier\CourierPassword;
use App\Models\Courier;
use App\Repositories\UserLogRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Repositories\CourierRepository;
use App\Http\Requests\Admin\Courier\ShowRequest;
use App\Http\Requests\Admin\Courier\QueryResource;
use App\Http\Requests\Admin\Courier\CourierCreate;
use App\Http\Requests\Admin\Courier\CourierUpdate;
use App\Http\Requests\Admin\Courier\CourierDestroy;

class CourierController extends Controller
{
    const BASE_PASSWORD = '123456';
    protected $courierRepository;
    protected $userLogRepository;

    /**
     * CouriersController constructor.
     * @param CourierRepository $courierRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        CourierRepository $courierRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->courierRepository = $courierRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取快递员列表资源列表
     *
     * Date: 2018/05/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $service_id = $request->get('service_id', false);
        $limit = $request->get('paginate', false);
        $name = $request->get('name', false);
        $created_at = $request->get('created_at', false);
        if ($service_id === null) {
            $service_id = false;
        }
        if ($name === null) {
            $name = false;
        }
        if ($created_at === null) {
            $created_at = false;
        }
        $couriers = $this->courierRepository->getCouriers($service_id, $limit, $name, $created_at);
        return success($couriers);
    }

    /**
     * 获取快递员详情
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function show(ShowRequest $request, $courier)
    {
        $limit = $request->get('paginate', 15);
        if (!is_numeric($courier)) {
            return failed('请上传正确的员工id', 422);
        }
        $couriers = $this->courierRepository->getCourierDetails($courier, $limit);
        if ($couriers) {
            return success($couriers);
        } else {
            return failed('该员工不存在！');
        }
    }


    /**
     * 创建快递员
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param CourierCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(CourierCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $couriers = $this->courierRepository->create($attributes);
        //记录日志
        $admins = Auth::guard('admin')->user();
        $uid = $admins->id;
        $service_id = $attributes['service_id'];
        $name = $admins->name;
        $operation = '添加了员工[' . $attributes['name'] . ']';
        $history = null;
        $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return stored($couriers);
    }

    /**
     * 更新快递员资源
     *
     * Date: 2018/05/11
     * @author Tenny
     * @param CourierUpdate $request
     * @param courier $courier
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function update(CourierUpdate $request, Courier $courier)
    {
        $couriersAttr = array_filter($request->only([
            'phone',
            'name',
            'work_status',
            'amount',
            'avatar',
            'status',
        ]), function ($value) {
            if ($value === null || $value === '') {
                return false;
            } else {
                return true;
            }
        });
        $courier->update($couriersAttr);
        //记录日志
        $admins = Auth::guard('admin')->user();
        $uid = $admins->id;
        $service_id = $courier->service_id;
        $name = $admins->name;
        $operation = '更新了员工[' . $courier->name . ']';
        $history = json_encode($courier->toArray(), true);
        $actuality = json_encode($couriersAttr, true);
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        $couriers = $this->courierRepository->getCourierDetails($courier->id, false);
        return updated($couriers);
    }

    /**
     * 删除 快递员 资源
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param CourierDestroy $request
     * @param Courier $courier
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(CourierDestroy $request, Courier $courier)
    {
        $force = $request->get('force');
        $force ? $courier->delete() : $courier->forceDelete();
        //记录日志
        $admins = Auth::guard('admin')->user();
        $uid = $admins->id;
        $service_id = $courier->service_id;
        $name = $admins->name;
        $operation = '删除了员工[' . $courier->name . ']';
        $history = null;
        $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }

    /**
     * 检测手机号码是否存在
     *
     * Date: 2018/06/10
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function existence(Request $request)
    {
        $this->validate($request, [
            'phone' => ['required', 'regex:/^(1[3456789])\d{9}$/', 'unique:courier,phone']
        ], [
            'phone.required' => '请输入手机号码',
            'phone.regex' => '您输入的手机号码有误',
            'phone.unique' => '您输入的手机号码已存在'
        ]);
        return message('可以注册');
    }

    /**
     * 重置密码
     *
     * Date: 2018/06/011
     * @author Tenny
     * @param CourierPassword $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function password(CourierPassword $request)
    {
        $params = $this->validate($request, [
            'courier_id' => 'required',
        ], [
            'courier_id.required' => '请上传员工id',
        ]);
        $courier = Courier::where('id', $params['courier_id'])->first();
        $courier->password = self::BASE_PASSWORD;
        $courier->save();
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = $courier->service_id;
        $name = $admin->name;
        $operation = '重置了员工[' . $courier->name . ']的密码';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return updated([], '该员工的密码修改成功');
    }
}
